package com.power.project.dao;

import com.power.project.model.Ww_depart_user;
import com.power.project.model.Ww_user;
import com.power.project.model.bo.DepartSaveuserBO;
import feign.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * 企业用户所在部门 持久层(hibernate)
 */

public interface Ww_depart_userDao extends JpaRepository<Ww_depart_user, Serializable>, JpaSpecificationExecutor<Ww_depart_user>, Repository<Ww_depart_user, Serializable>, Ww_depart_userDaoCustom<Ww_depart_user, Serializable> {

    @Transactional
    @Modifying
    @Query("update Ww_depart_user w set w.isleader = 1 where w.wwuserid in ?1 and w.departid = ?2 and w.tenantid = ?3")
    int updateIsLeader(Collection<String> wwuserids, String departId, String tenantId);


    @Transactional
    @Modifying
    @Query("update Ww_depart_user w set w.isleader = 0 where w.departid = ?1 and w.tenantid = ?2")
    int updateNotLeader(String departId, String tenantId);

    @org.springframework.transaction.annotation.Transactional
    @Modifying
    @Query("delete from Ww_depart_user w where w.wwuserid = ?1 and w.tenantid = ?2")
    void deleteByUserIdAndTenantId(String userId, String tenantId);

    @Transactional
    @Modifying
    @Query("delete from Ww_depart_user w where w.departid = :departId and w.wwuserid in (:userIds) and w.tenantid = :tenantId")
    void removeByDepartIdAndUserIds(String departId, List<String> userIds, String tenantId);

    @Transactional
    @Modifying
    @Query(value = "INSERT INTO Ww_depart_user (wwuserid, departid, isleader, tenantid) VALUES " +
            "((:#{#saveuserBO.getUserIds()}), :#{#saveuserBO.getDepartId()}, " +
            ":#{#saveuserBO.getIsleader()}, :#{#saveuserBO.getTenantid()})", nativeQuery = true)
    void saveByDepartIdAndUserIds(@Param("saveuserBO") DepartSaveuserBO saveuserBO);


    @Modifying
    @Query("from  Ww_user  where userid  not in (SELECT DISTINCT w.wwuserid from Ww_depart_user w where w.departid = ?1)")
    List<Ww_user> queryUsers(String departId);



    @Query("SELECT d.wwuserid FROM Ww_depart_user d WHERE d.departid = ?1")
    List<String> findWwuseridByDepartid(String departId);



    @Transactional
    @Query(value = "delete from Ww_depart_user w where w.departid = ?1 and wwuserid in (?2)",nativeQuery = true)
    @Modifying
    void deleteByDepartIdAndWwuserids(String departId, List<String> userIds);

    @Modifying
    @Query("from Ww_user where userid  in (?1)")
    List<Ww_user> findByUserId(List<String> userIds);
}
